package com.changgou.order.service.impl;

import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.feign.SpuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.goods.pojo.Spu;
import com.changgou.order.pojo.OrderItem;
import com.changgou.order.service.CartService;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 描述
 *
 * @author ljh
 * @version 1.0
 * @package com.changgou.order.service.impl *
 * @Date 2019-12-5
 * @since 1.0
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private SpuFeign spuFeign;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void add(String username, Long id, Integer num) {


        //判断 如果num <=0  删除掉原来的数据
        if (num <= 0) {
            //删除购物车中的商品
            redisTemplate.boundHashOps("Cart_" + username).delete(id);
            return;
        }


        //1.根据商品的SKU的ID 获取SKU的数据
        Result<Sku> skuResult = skuFeign.findById(id);
        Sku sku = skuResult.getData();
        //2.将数据存储到REDIS中 spring data redis  key: 用户名  field:sku的ID  value orderItem对象存储数据

        OrderItem orderItem = new OrderItem();
        //将sku的数据转成orderitem
        //要根据spu的ID 获取SPU的数据再获取分类的ID
        Result<Spu> spuResult = spuFeign.findById(sku.getSpuId());
        Spu spu = spuResult.getData();
        //shezhi ID
        orderItem.setCategoryId1(spu.getCategory1Id());
        orderItem.setCategoryId2(spu.getCategory2Id());
        orderItem.setCategoryId3(spu.getCategory3Id());
        orderItem.setSpuId(sku.getSpuId());
        orderItem.setSkuId(sku.getId());//
        orderItem.setName(sku.getName());//名称
        orderItem.setPrice(sku.getPrice());//价格
        orderItem.setNum(num);//数量
        orderItem.setMoney(num * sku.getPrice());//小结
        orderItem.setPayMoney(num * sku.getPrice());//实付金额
        orderItem.setImage(sku.getImage());//图片的地址

        redisTemplate.boundHashOps("Cart_" + username).put(id, orderItem);
    }

    @Override
    public List<OrderItem> findCartList(String username) {

        //hset key field1 value  --->
        // hget key field1 --->field1 对应的值
        List<OrderItem> values = redisTemplate.boundHashOps("Cart_" + username).values();
        return values;
    }
}
